package com.wyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.wyy.beans.Role;
import com.wyy.beans.UserRole;
import com.wyy.common.Result;
import com.wyy.dao.ResourceRoleDao;
import com.wyy.dao.RoleDao;
import com.wyy.dao.UserRoleDao;
import com.wyy.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private ResourceRoleDao resourceRoleDao;

    @Override
    public Result<Role> addRole(Role role) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "role_name", role.getRoleName());
        Role newRole = roleDao.selectOne(queryWrapper);
        if (newRole != null) {
            return new Result<>(Result.ResultStatus.Failed.code, "已存在");
        }

        int aff = roleDao.insert(role);
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Role> updateRole(Role role) {
        int aff = roleDao.updateById(role);
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Role> deleteRole(long rid) {
        roleDao.deleteById(rid);
        userRoleDao.deleteUserRoleByRoleId(rid);
        resourceRoleDao.deleteResourceRoleByRoleId(rid);
        return new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public List<Role> getRoleByUserId(long uid) {
        return Optional.ofNullable(roleDao.getRolesByUserId(uid)).orElse(Collections.emptyList());
    }

    @Override
    public Result<Role> getRoleById(long rid) {
        Role role = roleDao.selectById(rid);
        return role == null ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success",role);
    }
}
